#include <iostream>
#include <istream>
#include <sstream>
#include "TxGrpc.h"

void ParseCmd(std::string& strCmd, std::vector<std::string>& params)
{
    std::istringstream is(strCmd);
    do
    {
        std::string param;
        is >> param;
        if (param.empty())
        {
            break;
        }
        params.push_back(param);
    } while (true);
};

void PrintHelp()
{
    std::cout << "command list:" << std::endl
        << "\tsend\t\t- sync call SendMessage,\t\tsend xxx" << std::endl
        << "\tsenda\t\t- async call SendMessage,\t\tsenda xxx" << std::endl
        << "\tsends\t\t- call SendStreamMessage,\t\tsends xxx" << std::endl;
};

void OnRecvMessage(const std::string &data)
{
    std::cout<<std::endl;
    std::cout<<"recv data > "<<data<<std::endl;
    std::cout<<std::endl;
}

int main(int argc, char *argv[])
{
    TxGrpc::sptr grpc = TxGrpc::create();
#if 0
    grpc->SetSSLKey("./server.crt", "./server.key", "./client.crt", "./client.key", "txgang.com");
#endif
    std::string ip = "127.0.0.1";
    int port = 50053;
    if(argc == 3)
    {
        ip = argv[1];
        port = atoi(argv[2]);
    }

    std::cout<<"client start ..."<<std::endl;
    grpc->Connect(ip.c_str(), port);
    grpc->SetClientRecvDataCallback(OnRecvMessage);

    PrintHelp();

    while (1)
    {
        std::string line;
        std::getline(std::cin, line);
        std::vector<std::string> params;
        ParseCmd(line, params);
        if (params.size() == 0)
        {
            PrintHelp();
            continue;
        }

        if (params[0] == "senda")
        {
            grpc->AsyncSendMData(params[1].c_str(), params[1].length());
        }
        else if (params[0] == "send")
        {
            std::string result = grpc->SendData(params[1].c_str(), params[1].length());
            std::cout << "sync result = " << result << std::endl;
        }
        else if (params[0] == "sends")
        {
            grpc->SendStreamData(params[1].c_str(), params[1].length());
        }
        else if (params[0] == "exit") {
            break;
        }
    }

    grpc->DisConnect();
    getchar();
    grpc.reset();
    return 0;
}